﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;

namespace Macaw.Moss2007.XmlSitemapSolution2
{
    public class ManageXmlSitemap : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {

        protected CheckBox cbEnabled;
        protected TextBox tbSiteUrl;

        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack && SPContext.Current != null && SPContext.Current.Site != null)
            {
                ShowData();
            }

            base.OnLoad(e);
        }

        public const string XMLSITEMAPENABLED = "XmlSitemapEnabled";
        public const string XMLSITEMAPURL = "XmlSitemapUrl";

        public void ShowData()
        {
            using (SPWeb rootweb = SPContext.Current.Site.OpenWeb())
            {
                bool XmlSitemapEnabled = false;
                if (rootweb.Properties.ContainsKey(XMLSITEMAPENABLED))
                {
                    if (!bool.TryParse((string)rootweb.Properties[XMLSITEMAPENABLED], out XmlSitemapEnabled))
                    {
                        XmlSitemapEnabled = false;
                    }
                }

                string XmlSitemapSiteUrl = string.Empty;
                if (rootweb.Properties.ContainsKey(XMLSITEMAPURL))
                {

                    XmlSitemapSiteUrl = rootweb.Properties[XMLSITEMAPURL];
                }
                if (string.IsNullOrEmpty(XmlSitemapSiteUrl))
                {
                    XmlSitemapSiteUrl = SPContext.Current.Site.Url;
                }

                cbEnabled.Checked = XmlSitemapEnabled;
                tbSiteUrl.Text = XmlSitemapSiteUrl;
            }
        }

        public void btnSave_Click(object sender, EventArgs e)
        {
            using (SPWeb rootweb = SPContext.Current.Site.OpenWeb())
            {
                rootweb.Properties[XMLSITEMAPENABLED] = cbEnabled.Checked.ToString();
                rootweb.Properties[XMLSITEMAPURL] = tbSiteUrl.Text;
                rootweb.Properties.Update();
                //rootweb.Update();
            }
            ShowData();
        }
    }
}
